package net.cyndeline.GUI.canvas

import javafx.scene.canvas.Canvas
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.image.Image

class CanvasPainter extends Painter {
  private var background: RGB = new RGB(0, 0, 0)
  private var text: RGB = new RGB(255, 255, 255)
  private var canvas: Option[Canvas] = None
  private var textSize = 12
  
  override def setBackgroundColor(r: Int, g: Int, b: Int) {
    background = new RGB(rgb(r), rgb(g), rgb(b))
  }
  
  override def setTextColor(r: Int, g: Int, b: Int) {
    text = new RGB(rgb(r), rgb(g), rgb(b))
  }
  
  override def setTextSize(size: Int) {
    textSize = size
  }
  
  override def setCanvas(c: Canvas) {
    canvas = Option(c)
  }
  
  /**
   * Clears an area the size of the canvas, starting in the
   * upper left corner.
   */
  override def clear() {
    if (canvas.isDefined) {
      val c = canvas.get
      val context = c.getGraphicsContext2D()
      context.clearRect(0, 0, c.getWidth(), c.getHeight())
    }
    
  }
  
  override def drawRectangle(width: Double, height: Double, startX: Int, startY: Int, alpha: Double = 1.0) {
    if (canvas.isDefined) {
      val buffer = canvas.get.getGraphicsContext2D()
      buffer.setFill(getColor(background))
      buffer.fillRect(startX, startY, width, height)
    }
  }
  
  override def drawImage(img: Image, startX: Double, startY: Double) {
    if (canvas.isDefined) {
      val buffer = canvas.get.getGraphicsContext2D()
      buffer.drawImage(img, startX, startY)
    }
  }
  
  override def printText(str: String, startX: Int, startY: Int) {
    if (canvas.isDefined) {
      val buffer = canvas.get.getGraphicsContext2D()
      buffer.setFill(getColor(text))
      buffer.setFont(Font.getDefault());
      buffer.fillText(str, startX, startY)
    }
  }
  
  private def getColor(rgb: RGB, alpha: Double = 1.0): Color = {
    Color.web("rgba(" + background.r + ", " + background.g + ", " + background.b + ", " + alpha + ")")
  }
  
  private def rgb(value: Int): Int = Math.max(0, Math.min(255, value))
  
  private class RGB(val r: Int, val g: Int, val b: Int)
}